<?php
/**
 * @title 5472. 重新排列字符串 - 原字符串上移动
 * @author start2004
 */


class Solution {

    /**
     * @param String $s
     * @param Integer[] $indices
     * @return String
     */
    function restoreString($s, $indices) {
        /**
         * @since 2020-07-26 键值
         */
        $keys = array_keys($indices);

        /**
         * @since 2020-07-26 字典为空停
         */
        while($keys){
            /**
             * @since 2020-07-26 抛出字典第一个字符
             */
            $key = array_pop($keys);

            /**
             * @since 2020-07-26 准备移动点位置, 和值
             */
            $moveKey = $key;
            $moveChar = $s[$moveKey];

            /**
             * @since 2020-07-26 挪动回到原点停止
             */
            while($key != $indices[$moveKey]){
                $nextKey = $indices[$moveKey];

                list($moveChar, $s[$nextKey]) = [$s[$nextKey], $moveChar];
                unset($keys[$moveKey]);

                /**
                 * @since 2020-07-26 下次循环移动点
                 */
                $moveKey = $nextKey;
            }

            /**
             * @since 2020-07-26 收官
             */
            unset($keys[$moveKey]);
            $s[$key] = $moveChar;
        }

        /**
         * @return
         */
        return $s;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.26.php
 */
$datas = [
    ["codeleet",[4,5,6,7,0,2,1,3]],
    ["abc", [0,1,2]],
    ["aiohn", [3,1,4,2,0]],
    ["aaiougrt", [4,0,2,6,7,3,1,5]],
    ["art", [1,0,2]],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->restoreString($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
